<?php
function team(){
	global $_SGET,$_SPOST,$_SREQUEST;
	global $auid,$valid;
	$id = $_SREQUEST['id'];
	$name = $_SGET['name'];
	$owner = $_SGET['owner'];

	$newplayer=$_SREQUEST['newplayer'];
	//should only be used to change players on the team since team creation happens
	//as a side affect from other stuff
	if ($_SERVER['REQUEST_METHOD']=="POST"){
		if($valid){
			// Get info about new player
			$query="SELECT * FROM players WHERE id='$newplayer'";
			$result=mysql_query($query);
			$row=mysql_fetch_assoc($result);
			$newprice=$row['price'];
			$newposs=$row['position'];
			// Check who plays at that possition at the moment
			$query = "SELECT * FROM teams WHERE id='$id' AND owner='$auid'";
			$assoc = mysql_fetch_assoc(mysql_query($query));
			$newposs = strtolower($newposs);
			$player = $assoc[$newposs];
			$bank = $assoc['bank'];
			// Get info about the old player
			$query = "SELECT * FROM players WHERE id='$player'";
			$assoc = mysql_fetch_assoc(mysql_query($query));
			$oldprice = $assoc['price'];
			$tmp = $bank+$oldprice-$newprice;
			$query = "SELECT drafts FROM teams WHERE id='$id' and owner='$auid'";
			$tmp2 = mysql_fetch_row(mysql_query($query));
			$drafts = $tmp2[0]-1;
			if($tmp>=0 && $drafts>=0){
				// purchase the player
				$query = "UPDATE teams SET drafts='$drafts', $newposs='$newplayer',
					 bank='$tmp' WHERE owner='$auid' AND id='$id'";
				mysql_query($query);
				$query="UPDATE players SET nrofteams=(nrofteams-1) WHERE id='$player'";
				mysql_query($query);
				$query="UPDATE players SET nrofteams=(nrofteams+1) WHERE id='$newplayer'";
				mysql_query($query);
				header("HTTP/1.0 200 OK");
			}else{
				header("HTTP/1.0 404 NOT FOUND");
			}
		}else{
			header("HTTP/1.0 401 UNAUTHORIZED");
		}
	}
	//view a team
	if ($_SERVER['REQUEST_METHOD']=="GET"){
		$where="WHERE 1 ";
		if ($id){
			$where.=" AND id='".$id."'";
		}
		if ($name){
			$where.=" AND name='".$name."'";
		}
		if ($owner){
			$where.=" AND owner='".$owner."'";
		}
		if (isset($_SGET['order'])){
			$order2=$order;
		}else{
			$order2="ASC";
		}
		if (isset($_SGET['sortby'])){
			$sortby2=$sortby;
		}else{
			$sortby2="name";
		}
		if (!$startat){
			$startat=0;
		}
		if (!$shownr){
			$shownr=30;
		}

		$query="SELECT * FROM teams ".$where." ORDER BY ".$sortby2." ".$order2." LIMIT ".$startat." , ".$shownr;
		$result = mysql_query($query);
		$rows = array();
		while($r = mysql_fetch_assoc($result)){
			$tempquery="SELECT * FROM leagues WHERE id=(SELECT leagueid FROM leagueplayers WHERE teamid='".$r['id']."')";
			$tempres=mysql_query($tempquery);
			$tempres=mysql_fetch_assoc($tempres);
			$r['league']=$tempres['id'];
			$rows[] = $r;
		}
		print json_encode($rows);
	}
}
?>